package org.kinglone.back.user.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.kinglone.back.loginLog.service.LoginLogService;
import org.kinglone.back.user.model.User;
import org.kinglone.back.user.service.UserService;
import org.kinglone.common.util.JSONMessageView;
import org.kinglone.common.util.PageQuery;
import org.kinglone.common.util.PageResults;
import org.kinglone.common.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/user")
public class UserAction {
	
	@Resource(name="userService")
	private UserService userService;
	
	@Resource(name="loginLogService")
	private LoginLogService loginLogService;	
	
	//跳转到后台主页
	@RequestMapping("/main.jspx")
	public ModelAndView main(HttpServletRequest request){
		ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/main/main.jsp");
		User user = (User) request.getSession().getAttribute("user");
		modelAndView.addObject("user", user);
		return modelAndView;
	}
	//登录
	@RequestMapping("/login.jspx")
	public JSONMessageView login(HttpServletRequest request,User user,@RequestParam("vcode") String vcode,HttpSession session){
		JSONMessageView json = new JSONMessageView(-1, "登录失败!", null);
		try {
			String sessionVcode = (String) session.getAttribute("vcode");			
			if (!vcode.equals(sessionVcode)) {
				json.setCode(-1);
				json.setMessage("您输入的验证码不正确,请核实!");
				return json;
			}
			session.removeAttribute("vcode");
			User u = userService.findUserInfo(user);
			
			if(u == null) {
				//获取外网ip
				String remoteIP = request.getRemoteAddr();
				//获取内网ip
				String clientIP = getIp(request);
				String status = "error";
				String username = request.getParameter("username");
				loginLogService.saveLoginLog(remoteIP,clientIP,status,username);												
				json.setCode(-1);
				json.setMessage("您输入的账号或者密码错误!");
				return json;
			}else {
				//获取外网ip
				String remoteIP = request.getRemoteAddr();
				//获取内网ip
				String clientIP = getIp(request);
				String status = "success";
				String username =u.getUsername();
				loginLogService.saveLoginLog(remoteIP,clientIP,status,username);
				session.setAttribute("user", u);				
				json.setCode(0);									
				json.setMessage("登录成功!");	
				return json;
			}			
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("登录失败!");
			return json;
		}
	}
	
	//获取内网ip
	public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtil.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
       /* return request.getRemoteAddr();*/
		return ip;
    }
	//退出登录
	@RequestMapping("/userLogout.jspx")
	public String userLogout(HttpServletRequest request) {
		//将session中用户信息清除
		request.getSession().removeAttribute("user");
		//清除cookie信息
		/*CookieUtils.removeCookie(,request,response);*/
				
		return "/login.jsp";
	} 
	//当前用户
	@RequestMapping("/home.jspx")
	public ModelAndView home(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("user");
		ModelAndView mv = new ModelAndView("/WEB-INF/jsp/back/user/home.jsp");
		mv.addObject("user", user);
		return mv;
	}
	
	//跳转到用户管理页面
	@RequestMapping("/selectUser.jspx")
	public ModelAndView selectUser(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/WEB-INF/jsp/back/user/user.jsp");
		return mv;
	}
	
	//分页查询用户列表
	@RequestMapping("/selUserList.jspx")
	public JSONMessageView selUserList(HttpServletRequest request) {
		JSONMessageView json = new JSONMessageView(-1, "查询失败!", null);
		try {
			String name = request.getParameter("name");
			String phone = request.getParameter("phone");
			String pageNo = request.getParameter("pageNo");
			String pageSize = request.getParameter("pageSize");
			PageQuery pageQuery = new PageQuery();
			pageQuery.setStart((Integer.parseInt(pageNo)-1)*Integer.parseInt(pageSize));
			pageQuery.setLength(Integer.parseInt(pageSize));
			PageResults<User> list = userService.findUserList(pageQuery,name,phone);
			JSONArray totalJsonArray = new JSONArray();
			JSONObject totalJsonObject = new JSONObject();
			JSONArray jsonArray=new JSONArray();
			for(User u : list.getResults()) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("sysid", u.getSysid());
				jsonObject.put("username", u.getUsername());
				jsonObject.put("likename", u.getLikename());
				jsonObject.put("sex",u.getSex());
				jsonObject.put("phone", u.getPhone());
				jsonObject.put("email", u.getEmail());
				jsonArray.add(jsonObject);
			}
			totalJsonObject.put("pagetotal", list.getPageCount());//总页数
			totalJsonObject.put("info", jsonArray);
			totalJsonArray.add(totalJsonObject);
			json.setCode(0);
			json.setMessage("查询成功!");
			json.setContent(totalJsonArray);
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("查询失败!");
			return json;
		}
		return json;
	}

	//跳转到添加用户页面
	@RequestMapping("/showAddUser.jspx")
	public ModelAndView showAddUser() {
		ModelAndView mv = new ModelAndView("/WEB-INF/jsp/back/user/addUser.jsp");
		return mv;
	}
	//异步查询账号是否注册
	@RequestMapping("/checkUserName.jspx")
	public JSONMessageView checkUserName(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1, "查询失败", null);
		try {
			String username= request.getParameter("username");
			User user = userService.findUserByUsername(username);
			if(user==null){
				json.setCode(0);
				json.setMessage("用户名可以使用!");
				return json;
			}else{
				json.setCode(-1);
				json.setMessage("用户名已注册!");
				return json;
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}
	}
	//添加用户
	@RequestMapping("/submitAddUser.jspx")
	public JSONMessageView submitAddUser(HttpServletRequest request,User user){
		JSONMessageView json = new JSONMessageView(-1,"添加失败!",null);
		try {
			userService.save(user);
			json.setCode(0);
			json.setMessage("添加成功!");
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试");
			return json;
		}
	}
	
	//跳转到修改用户页面
	@RequestMapping("/showUpdateUser.jspx")
	public ModelAndView showUpdateUser(String userId,Model model) {
		ModelAndView mv = new ModelAndView("/WEB-INF/jsp/back/user/updateUser.jsp");
		User user = userService.get(userId);
		mv.addObject("user", user);
		return mv;
	}
	
	@RequestMapping("/updateUser.jspx")
	public JSONMessageView updateUser(HttpServletRequest request){
		JSONMessageView json = new JSONMessageView(-1, "修改失败!", null);
		try {
			String userId = request.getParameter("userId");
			String likename = request.getParameter("likename");
			String sex = request.getParameter("sex");
			String email = request.getParameter("email");
			String phone = request.getParameter("phone");
			if(StringUtil.isNullOrEmpty(userId)){
				return new JSONMessageView(-1, "请选择修改的用户!", null);
			}
			if(StringUtil.isNullOrEmpty(likename)){
				return new JSONMessageView(-1, "请输入昵称!", null);
			}
			if(StringUtil.isNullOrEmpty(sex)){
				return new JSONMessageView(-1, "请选择性别!", null);
			}
			if(StringUtil.isNullOrEmpty(email)){
				return new JSONMessageView(-1, "请输入邮箱!", null);
			}
			if(StringUtil.isNullOrEmpty(phone)){
				return new JSONMessageView(-1, "请输入手机号!", null);
			}			
			User user = userService.get(userId);
			user.setLikename(likename);
			user.setEmail(email);
			user.setSex(sex);
			user.setPhone(phone);
			userService.update(user);
			json.setCode(0);
			json.setMessage("修改成功!");
			return json;
 			
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}
	}
	
	
	//跳转到预览用户页面
	@RequestMapping("/preUser.jspx")
	public ModelAndView preUser(String userId) {
		ModelAndView mv = new ModelAndView("/WEB-INF/jsp/back/user/preUser.jsp");
		User user = userService.get(userId);
		mv.addObject("user", user);
		return mv;
	}
	
	//删除用户
	@RequestMapping("/delUser.jspx")
	public JSONMessageView delUser(String userId){
		JSONMessageView json = new JSONMessageView(-1, "删除失败!", null);
		try {
			if(StringUtil.isNullOrEmpty(userId)) {
				json.setMessage("未取得参数");
				return json;
			}
			userService.deleteById(userId);
			json.setCode(0);
			json.setMessage("删除成功！");
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.setCode(-1);
			json.setMessage("服务器异常,请稍候再试!");
			return json;
		}
	}

	
}
